//
//  JourneyContactInfoViewController.m
//  MyTravel
//
//  Created by Hunk on 11-5-25.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "JourneyContactInfoViewController.h"
#import "NetworkManager.h"
#import "MyLoadingView.h"

#define KEY_NAME   @"name"

#define KEY_MOBILE @"mobile"
#define KEY_WORK   @"workPhone"
#define KEY_QQ     @"qq"
#define KEY_FAX    @"fax"
#define KEY_EMAIL  @"email"

#define MESSAGEBODY @"我有以下问题想要资询:<点击此处写入内容>\n"

#define TAG_TABLEVIEW (31)

@interface JourneyContactInfoViewController (Private)

-(void)addLabelOnCell:(UITableViewCell*)cell
                 text:(NSString*)text
                frame:(CGRect)frame 
              bgColor:(UIColor*)bgColor 
            textColor:(UIColor*)textColor 
           fontOfSize:(UIFont*)fontOfSize 
        lineBreakMode:(UILineBreakMode)lineBreakMode 
        textAlignment:(UITextAlignment)textAlignment;

- (void)displayComposerSheet:(NSString*)emailAddress;


- (void)launchMailAppOnDevice:(NSString*)emailAddress;

@end;

@implementation JourneyContactInfoViewController
@synthesize journeyTitle, journeyId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    SAFE_RELEASE(arrayContacts)
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:@"联系方式"];
    [self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
    
    arrayContacts = [[NSMutableArray alloc] init];
    
    // Add tableView
    UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)
                                                          style:UITableViewStyleGrouped];
    //tableView.backgroundColor = [UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    [tableView setTag:TAG_TABLEVIEW];
    [self.view addSubview:tableView];
    [tableView release];
    
    // Data
    NSDictionary* parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                journeyId, @"journeyId", nil];
    
    [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetJourneyContactInfo
                                                   WithParameters:parameters
                                                 AndCallBackScope:self
                                                    AndSuccessSel:@"onSuccess:"
                                                     AndFailedSel:@"onFailed:"];
    [[MyLoadingView sharedMyLoadingView] startLoadingAnimation];
}

#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{   
    return [arrayContacts count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return [[[arrayContacts objectAtIndex:0] allKeys] count] - 1;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 30.0f;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{	
    return 60.0f;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[arrayContacts objectAtIndex:section] objectForKey:KEY_NAME];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier:CellIdentifier] autorelease];
     
    switch (indexPath.row)
    {
        case 0: // Mobile
        case 1: // Work
        case 4: // Email
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            break;
        case 2: // QQ
        case 3: // Fax
            cell.accessoryType = UITableViewCellAccessoryNone;
            break;
        default:
            break;
    }
    // Get one contact
    NSDictionary* contactDictionary = [arrayContacts objectAtIndex:indexPath.section];
    
//    // Cell Background view
//    UIView* cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
//    UIImageView* bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
//    [bgImageView setImage:[UIImage imageNamed:@"CellBackground.png"]];
//    [cellBgView addSubview:bgImageView];
//    [bgImageView release];
//    [cell setBackgroundView:cellBgView];
//    [cellBgView release];
    
    // Keys for contact image and label text
    NSArray* arrayKeys = [NSArray arrayWithObjects:KEY_MOBILE, KEY_WORK, KEY_QQ, KEY_FAX, KEY_EMAIL, nil];
    
    // Contact imageView
    NSString* nameString = [NSString stringWithFormat:@"%@.png", [arrayKeys objectAtIndex:indexPath.row]];
    UIImage* mobileImage = [UIImage imageNamed:nameString];
    UIImageView* mobileImageView = [[UIImageView alloc] initWithImage:mobileImage];
    [mobileImageView setFrame:CGRectMake(10, 10, mobileImage.size.width, mobileImage.size.height)];
    mobileImageView.backgroundColor = [UIColor clearColor];
    [cell.contentView addSubview:mobileImageView];
    [mobileImageView release];
    
    // Contact label
    [self addLabelOnCell:cell
                    text:[contactDictionary objectForKey:[arrayKeys objectAtIndex:indexPath.row]] 
                   frame:CGRectMake(50, 10, 225, 40)
                 bgColor:[UIColor clearColor] 
               textColor:TEXTCOLOR
              fontOfSize:[UIFont fontWithName:@"AmericanTypewriter" size:20]
           lineBreakMode:UILineBreakModeTailTruncation
           textAlignment:UITextAlignmentRight];
    
    return cell;

}

#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.row)
    {
        case 0: // Mobile
        {
            if([[UIDevice currentDevice].model isEqualToString:@"iPhone"])
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", [[arrayContacts objectAtIndex:indexPath.section] objectForKey:KEY_MOBILE]]]];
            }
            else
            {
                ALERT_GENERAL(@"貌似您的设备不支持电话功能")
            }
        }
            break;
        case 1: // Work
        {
            if([[UIDevice currentDevice].model isEqualToString:@"iPhone"])
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", [[arrayContacts objectAtIndex:indexPath.section] objectForKey:KEY_WORK]]]];
            }
            else
            {
                ALERT_GENERAL(@"貌似您的设备不支持电话功能")
            }
        }
            break;
        case 4: // Email
        {
            Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
            if(mailClass)
            {
                if([mailClass canSendMail])
                    [self displayComposerSheet:[[arrayContacts objectAtIndex:indexPath.section] objectForKey:KEY_EMAIL]];
                else
                    [self launchMailAppOnDevice:[[arrayContacts objectAtIndex:indexPath.section] objectForKey:KEY_EMAIL]];
            }
            else
                [self launchMailAppOnDevice:[[arrayContacts objectAtIndex:indexPath.section] objectForKey:KEY_EMAIL]];
        }
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark addLabelOnCell
-(void)addLabelOnCell:(UITableViewCell*)cell
				 text:(NSString*)text
				frame:(CGRect)frame 
			  bgColor:(UIColor*)bgColor 
			textColor:(UIColor*)textColor 
		   fontOfSize:(UIFont*)fontOfSize 
		lineBreakMode:(UILineBreakMode)lineBreakMode 
		textAlignment:(UITextAlignment)textAlignment
{
	if(!bgColor) bgColor = [UIColor grayColor];
	if(!textColor) textColor = [UIColor blackColor];
	if(!fontOfSize) fontOfSize = [UIFont systemFontOfSize:16];
	if(!text) text = [NSString stringWithString:@"请输入Label内容"];
	
	UILabel* titleLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
	titleLabel.backgroundColor = bgColor;
	titleLabel.textColor = textColor;
	titleLabel.font = fontOfSize;
	titleLabel.lineBreakMode = lineBreakMode;
	titleLabel.textAlignment = textAlignment;
	titleLabel.text = text;
	[cell.contentView addSubview:titleLabel];
}

#pragma mark -
#pragma mark Compose Mail
-(void)displayComposerSheet:(NSString*)emailAddress 
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
    picker.navigationBar.tintColor = TINTCOLOR;
	
	[picker setSubject:[NSString stringWithFormat:@"咨询<%@>", journeyTitle]];
	
	// Set up recipients
    [picker setToRecipients:[NSArray arrayWithObjects:emailAddress, nil]];
    
	// Fill out the email body text
	[picker setMessageBody:MESSAGEBODY isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
    [picker release];
}

#pragma mark -
#pragma mark Workaround
// Launches the Mail application on the device.
-(void)launchMailAppOnDevice:(NSString*)emailAddress 
{	
	// Recipient(s)
	NSString* strRecipient = [NSString stringWithFormat:@"mailto:%@?subject=%@", emailAddress, [NSString stringWithFormat:@"咨询<%@>", journeyTitle]];
	
	// Mail body
	NSString* strBody = [NSString stringWithFormat:@"&body=%@", MESSAGEBODY];
	
	NSString* strEmail = [NSString stringWithFormat:@"%@%@", strRecipient, strBody];
	strEmail = [strEmail stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:strEmail]];
}

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{		
    NSString* strSendEmailresult = nil;
    switch (result)
    {
        case MFMailComposeResultCancelled: 
            strSendEmailresult = @"操作已被取消";
            break;
        case MFMailComposeResultSaved:
            strSendEmailresult = @"邮件已被保存到草稿箱";
            break;
        case MFMailComposeResultSent:
            strSendEmailresult = @"邮件正在发送,请保持网络通畅";
            break;
        case MFMailComposeResultFailed:
            strSendEmailresult = @"邮件发送失败，请重新发送";
            break;
        default:
            break;
    }
    
//    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:strSendEmailresult 
//                                                    message:nil 
//                                                   delegate:nil
//                                          cancelButtonTitle:@"好的" 
//                                          otherButtonTitles:nil];
//    [alert show];
//    [alert release];
    
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark NetworkManager callback Methods
- (void)onSuccess:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    [arrayContacts removeAllObjects];
    [arrayContacts addObjectsFromArray:[resultDic objectForKey:@"journeyContactInfo"]];
    
    UITableView* tableView = (UITableView*)[self.view viewWithTag:TAG_TABLEVIEW];
	[tableView reloadData];
}

- (void)onFailed:(id)sender
{
	NSDictionary* resultDic = (NSDictionary*)sender;
    
    // 暂无数据提示
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:SORRY_NODATA 
                                                        message:[resultDic objectForKey:@"message"]
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

#pragma mark scrollViewDidScroll 上拉刷新
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
